import React from "react";
import {
  DndContext,
  closestCenter,
  MouseSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from "@dnd-kit/core";
import {
  SortableContext,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import useGetPageInfo from "../../../hooks/useGetPageInfo";

type PropsType = {
  children: JSX.Element | JSX.Element[];
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  items: Array<{ id: string; [key: string]: any }>;
  onDragEnd: (oldIndex: number, newIndex: number) => void;
};

const SortableContainer: React.FC<PropsType> = (props: PropsType) => {
  const { children, items, onDragEnd } = props;
  const { isPublished } = useGetPageInfo();
  const sensors = useSensors(
    useSensor(MouseSensor, {
      // 拖拽约束
      activationConstraint: {
        // 移动8px激活拖拽
        distance: 8,
      },
    })
  );

  function handleDragEnd(event: DragEndEvent) {
    const { active, over } = event;
    if (!over) return;
    if (active.id !== over.id) {
      const oldIndex = items.findIndex((i) => i.id === active.id);
      const newIndex = items.findIndex((i) => i.id === over.id);

      onDragEnd(oldIndex, newIndex);
    }
  }

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragEnd={handleDragEnd}
    >
      <SortableContext
        items={items}
        strategy={verticalListSortingStrategy}
        disabled={isPublished} // 已发布时，禁用拖拽功能
      >
        {children}
      </SortableContext>
    </DndContext>
  );
};

export default SortableContainer;
